package com.lq;

import java.io.IOException;
import java.io.Reader;

public class CloneReader {

    private static final int MAX_ALLOWED_SIZE = 40960;

    public static Reader[] clone(Reader src) throws IOException
    {
        char[] buffer = new char[MAX_ALLOWED_SIZE];
        int read = src.read(buffer, 0, MAX_ALLOWED_SIZE);
        if (read >= MAX_ALLOWED_SIZE - 1) {
            throw new RuntimeException("Source exceeds maximum allowed size of " + MAX_ALLOWED_SIZE + " characters");
        }
        final char[] actual;
        if (read == -1) {
            actual = new char[0];
        } else {
            actual = new char[read];
            System.arraycopy(buffer, 0, actual, 0, read);
        }
        return new Reader[]{doCreateReader(actual), doCreateReader(actual)};
    }

    private static Reader doCreateReader(char[] content)
    {
        return new Reader() {

            private int pos = 0;

            @Override
            public int read(char[] cbuf, int off, int len)
            {
                if (pos >= content.length) {
                    return -1;
                }
                int remaining = content.length - pos;
                int bytesToRead = Math.min(len, remaining);
                System.arraycopy(content, pos, cbuf, off, bytesToRead);
                pos += bytesToRead;
                return bytesToRead;
            }

            @Override
            public void close()
            {
            }

        };
    }

}
